package com.example.common;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author ：伍绍恒
 * @date ：Created in 2022/11/26 23:28
 * @description：全局异常拦截类-导入数据出现重复id主键冲突时，做统一处理
 * @modified By：
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)//指明要拦截哪些异常
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        //报错包含Duplicate entry表示为账号已存在
        if (ex.getMessage().contains("Duplicate entry")) {
            //分割异常报错信息，提取出重复的id
            //【0】Duplicate 【1】entry 【2】'1231' for key 'idx_username'
            final String[] split = ex.getMessage().split(" ");
            String msg = split[2];
            return R.error(msg);
        }
        return R.error("未知错误！请稍后重试");
    }

    @ExceptionHandler(Exception.class)
    public R<String> exceptionHandler2(Exception e) {
        System.err.println("全局异常接管处理！");
        return R.error("AllExceptionControl!");
    }
}
